package com.wzg.mytableview.handler;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.Button;

import com.wzg.mytableview.R;

import java.util.Timer;
import java.util.TimerTask;

/**
 * author：wzg
 * date:
 * desc:
 */
public class HandlerActivity extends AppCompatActivity {


    private Button mButton;
    private Button mTimer;
    //60秒
    private int time = 20000;

    private final Handler handler = new Handler(Looper.getMainLooper());


    private final Runnable runnable = new Runnable() {
        @SuppressLint("SetTextI18n")
        @Override
        public void run() {

            time -= 1000;
            runOnUiThread(() -> {
                if (time == 0) {
                    time = 6000;
                    mButton.setText("action");
                    mButton.setEnabled(true);
                    handler.removeCallbacks(this);
                } else {
                    mButton.setText((time / 1000) + "s");
                    //递归运行
                    handler.postDelayed(this, 1000);
                }

            });

        }
    };


    private Timer timer = new Timer();

    private final TimerTask timerTask = new TimerTask() {
        @SuppressLint("SetTextI18n")
        @Override
        public void run() {
            time -= 1000;
            runOnUiThread(() -> {
                if (time == 0) {
                    time = 6000;
                    timer.cancel();
                    mTimer.setText("action");
                    mTimer.setEnabled(true);
                } else {
                    mTimer.setText((time / 1000) + "s");
                }

            });
        }
    };


    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        setTitle("倒计时");

        mButton = findViewById(R.id.action);
        mTimer = findViewById(R.id.action1);

        mButton.setOnClickListener(v -> {
            handler.postDelayed(runnable, 1000);
            mButton.setText((time / 1000) + "s");
            mButton.setEnabled(false);
        });


        mTimer.setOnClickListener(v -> {
            timer.schedule(timerTask, 1000, 1000);
            mTimer.setText((time / 1000) + "s");
            mTimer.setEnabled(false);
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (handler != null) handler.removeCallbacks(runnable);
        if (timer != null) timer.cancel();
    }
}